package com.heima.common.exception;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
@Configuration
public class ExceptionCatch {

    /**
     * 未知异常
     * 拦截给用户友善信息
     *
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult unknownExceptionHandler(Exception e) {
        log.error("Exception e: {}", e);
        e.printStackTrace();
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "网络异常，请稍后再试");
    }

    /**
     * 预知异常拦截
     * 当 CustomException是Exception的子类时，先执行子类的拦截方法
     *
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public ResponseResult customExceptionHandler(CustomException e) {
        System.out.println(e.getAppHttpCodeEnum().getErrorMessage());
        log.error("CustomException e: {}", e);
        return ResponseResult.errorResult(e.getAppHttpCodeEnum());
    }
}
